package com.xscr.api.utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * <p>
 * Title: RSA非对称型加密的公钥和私钥
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2003
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author not attributable
 * @version 1.0
 */

public class RSAUtil {
 private static KeyPairGenerator kpg = null;
 private static KeyPair kp = null;
 private static  PublicKey public_key = null;
 private static PrivateKey private_key = null;

 /**
  * 构�?函数
  * 
  * @param in
  *            指定密匙长度（取值范围：512�?048�?
  * @throws NoSuchAlgorithmException
  *             异常
  */
 static void init(int in,String address)throws NoSuchAlgorithmException,FileNotFoundException, IOException{
  kpg = KeyPairGenerator.getInstance("RSA"); // 创建‘密匙对’生成器
  kpg.initialize(in); // 指定密匙长度（取值范围：512�?048�?
  kp = kpg.genKeyPair(); // 生成‘密匙对’，其中包含�?��个公匙和�?��私匙的信�?
  public_key = kp.getPublic(); // 获得公匙
  private_key = kp.getPrivate(); // 获得私匙

  sun.misc.BASE64Encoder b64 = new sun.misc.BASE64Encoder();
  String pkStr = b64.encode(public_key.getEncoded());
  String prStr = b64.encode(private_key.getEncoded());
  System.out.print("pkStr length:" + pkStr.length() + pkStr);

  FileWriter fw = new FileWriter(address + "/private_key.dat");
  fw.write(prStr);
  fw.close();

  FileWriter fw2 = new FileWriter(address + "/public_key.dat");
  fw2.write(pkStr);
  fw2.close();
 }
 public RSAUtil(int in, String address)  {
  
 }

 /**
  *加密的方�?
  */
 private  static String encrypt(String source) throws Exception{
    
    /** 将文件中的公钥对象读�?*/
   FileReader  fr = new FileReader("e://public_key.dat");
   BufferedReader br=new BufferedReader(fr);//建立BufferedReader对象，并实例化为br
    String getPbKey = "";
      while(true){
       String aLine = br.readLine();
       if(aLine==null)break;
       getPbKey += aLine;
   }
      System.out.println( "myBuilderStr :  length: " +  getPbKey.length() +" :"+getPbKey ); 
       BASE64Decoder   b64d = new  BASE64Decoder();
      byte [] keyByte =  b64d.decodeBuffer(getPbKey); 
      X509EncodedKeySpec  x509ek  = new X509EncodedKeySpec(keyByte);
      KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
      PublicKey  publicKey = keyFactory.generatePublic(x509ek);
      
      Cipher cipher = Cipher.getInstance("RSA"); 
      cipher.init(Cipher.ENCRYPT_MODE,publicKey); 
     byte[] sbt = source.getBytes();
     byte [] epByte = cipher.doFinal(sbt); 
     BASE64Encoder encoder = new BASE64Encoder();
     String epStr =  encoder.encode(epByte);
     return epStr;

 }

 /**
  *解密的方�?
  */
 public static String decrypt(String cryptograph) throws Exception{ 
    
    FileReader  fr = new FileReader("e://private_key.dat");
    BufferedReader br=new BufferedReader(fr);//建立BufferedReader对象，并实例化为
     String getPvKey = "";
       while(true){
        String aLine = br.readLine();
        if(aLine==null)break;
        getPvKey += aLine;
    }
         BASE64Decoder   b64d = new  BASE64Decoder();
        byte [] keyByte =  b64d.decodeBuffer(getPvKey); 
        PKCS8EncodedKeySpec  s8ek  = new PKCS8EncodedKeySpec(keyByte);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
        PrivateKey  privateKey = keyFactory.generatePrivate(s8ek);
     
       
    /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] b1 = decoder.decodeBuffer(cryptograph);
    /** 执行解密操作 */
    byte[] b = cipher.doFinal(b1);
    return new String(b);
 }

 public static void main(String[] args) throws Exception{
  /*try {
   new RSAUtil(1024, "D:/"); // 私匙和公匙保存到D盘下的文件中.
   System.out.println("");
   String getEptStr = encrypt("fengyupeng");
   System.out.println("getEptStr:" + getEptStr);
   String drpStr = decrypt(getEptStr);
   System.out.println("drpStr:" + drpStr);
  } catch (IOException ex) {
   ex.printStackTrace();
  } catch (NoSuchAlgorithmException ex) {
   ex.printStackTrace();
  } catch (Exception ex) {
   ex.printStackTrace();
  }*/
  init(1024, "e:/");
  
//  String getEptStr = encrypt("fengyupeng");
//  System.out.println("getEptStr:" + getEptStr);
//  String drpStr = decrypt(getEptStr);
//  System.out.println("drpStr:" + drpStr);
 }

}